package com.aliyun.heiyu.powermaster.server.service;


import com.aliyun.heiyu.common.util.JdbcUtil;
import com.aliyun.heiyu.common.util.PropertiesUtil;
import com.aliyun.heiyu.powermaster.server.util.Configuration;
import com.aliyun.heiyu.powermaster.server.util.ZkClientUtil;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: ZookeeperProviderImpl
 * @Author: majun
 * @Description: TODO
 * @Date: Created in 2019/11/5 16:26
 */
public class ZookeeperProviderImpl implements ZookeeperProvider {

    private static Logger logger = LoggerFactory.getLogger(ZookeeperProviderImpl.class);

    private final static Integer ZK_LOCAL_PORT = Integer.valueOf(PropertiesUtil.getValue("zoo.properties", "clientPort"));
    private final static String LEADER_PATH = "/leader";
    private final static String ZK_LOCAL_IP = Configuration.IP;

    public ZookeeperProviderImpl() {
        heart();
    }


    public void heart() {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    updateLeaderIp();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1, new BasicThreadFactory.Builder().namingPattern("zk-chose-leader-pool-%d").daemon(true).build());
        service.scheduleAtFixedRate(runnable, 60, 5, TimeUnit.SECONDS);

    }

    private void updateLeaderIp() throws Exception {
        String cmd = "stat";
        BufferedReader reader = null;
        Socket sock = null;
        try {
            sock = new Socket(ZK_LOCAL_IP, ZK_LOCAL_PORT);
            OutputStream outstream = sock.getOutputStream();
            // 通过Zookeeper的四字命令获取服务器的状态
            outstream.write(cmd.getBytes());
            outstream.flush();
            sock.shutdownOutput();

            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.indexOf("Mode: ") != -1) {
                    String temp = line.replaceAll("Mode: ", "").trim();
                    if (temp.equals("leader")) {
                        ZkClientUtil.updateNodeData(LEADER_PATH, ZK_LOCAL_IP);
                        String sql = "replace INTO zk_leader(id, leader)VALUES(1, ?)";
                        Object[] params = new Object[1];
                        params[0] = ZK_LOCAL_IP;
                        JdbcUtil.update(sql, params);
                    }
                }
            }
        } finally {
            if (sock != null && !sock.isClosed()) {
                try {
                    sock.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }


}
